介紹
狀態模式讓物件的行為隨著內部狀態不同而改變。
C++範例
#include <iostream>
#include <string>
class PlayerState
{
public:
PlayerState(const std::string& stateName) : m_stateName(stateName)
{
}
virtual ~PlayerState() {}
virtual void Attack() = 0;
virtual void Duck() = 0;
std::string GetStateName() const
{
return m_stateName;
}
private:
const std::string m_stateName;
};
class JumpState : public PlayerState
{
public:
JumpState() : PlayerState("Jumping")
{
}
~JumpState() {}
void Attack() override
{
std::cout << "Use jump kick" << std::endl;
}
void Duck() override
{
std::cout << "(Player is jumping, can't duck)" << std::endl;
}
};
class DuckState : public PlayerState
{
public:
DuckState() : PlayerState("Ducking")
{
}
~DuckState() {}
void Attack() override
{
std::cout << "Use duck kick" << std::endl;
}
void Duck() override
{
std::cout << "(Player is ducking, can't duck again)" << std::endl;
}
};
class Player
{
public:
Player(){};
virtual ~Player() {}
void SetState(PlayerState *state)
{
m_state = state;
std::cout << "-- The player is in " + m_state->GetStateName() + " state" << std::endl;
}
void Attack()
{
m_state->Attack();
}
void Duck()
{
m_state->Duck();
}
private:
PlayerState *m_state;
};
int main()
{
JumpState jumpState;
DuckState duckState;
Player player;
// 設定玩家正在跳躍狀態
player.SetState(&jumpState);
player.Attack();
player.Duck();
// 設定玩家正在蹲下狀態
player.SetState(&duckState);
player.Attack();
player.Duck();
return 0;
}
Output:
-- The player is in Jumping state
Use jump kick
(Player is jumping, can't duck)
-- The player is in Ducking state
Use duck kick
(Player is ducking, can't duck again)